package com.mot.j2me.midlets;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;


import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;//falls under jsr 037
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
//import javax.microedition.lcdui.List;
//import javax.microedition.lcdui.Ticker;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.location.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;


public class LocationDemo extends MIDlet implements CommandListener {
    private Display display;
    private Form form;
    private Command cmdBack,cmdOK, cmdExit;
    private StringItem si;
    String query;
    
    public ChoiceGroup menu = null;
    /**
     * Ok Command, used to select a Font face
     */
   // private Command okCommand = new Command("SELECT", Command.OK, 1);
   
    public LocationDemo() {
        display =Display.getDisplay(this);
        form = new Form("Welcome to Mlbs Demo");
        cmdOK = new Command("OK",Command.OK,0);
        cmdBack = new Command("Back",Command.BACK,1);
        //cmdExit = new Command("Exit",Command.EXIT,2);
        
        
        si = new StringItem("", "");
        form.append(si);
        mainMenu();
        
        //form.setCommandListener(this);
    }
    
    
    /**
     * Test the List component.
     */
    public void mainMenu(){
        menu = new ChoiceGroup("Choose Items", Choice.EXCLUSIVE);
        //menu.setTicker(new Ticker("listTest"));
        form.addCommand(cmdOK);
        form.addCommand(cmdBack);
        form.setCommandListener(this);
        menu.append("Restaurant", null);
        menu.append("Hospital", null);
        menu.append("Starbucks", null);
        menu.append("School", null);
        form.append(menu);
        
        
    }

    protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
         notifyDestroyed();
    }

    protected void pauseApp() {
        // TODO Auto-generated method stub
    }

    protected void startApp() throws MIDletStateChangeException {
        display.setCurrent(form);
    }

    public void commandAction(Command c, Displayable d) {
       
    	String label = c.getLabel();
    	System.out.println("label:"+label);

    	
    	if (c == cmdOK){
            try {
            	int index = menu.getSelectedIndex();
            	System.out.println("index:"+index);
            	switch(index){
	            	case 0: 
	            		query = "restaurant";
	            		break;
	            	case 1: 
	            		query = "hospital";
	            		break;
	            	case 2: 
	            		query = "starbucks";
	            		break;
	            	case 3: 
	            		query = "school";
	            		break;
	            	default: 
	            		query = "gas";
            	}
            	form.delete(1);
            	Retriever ret = new Retriever(this, query);
                ret.start();
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (c == cmdExit) {
            try {
                destroyApp(true);
                notifyDestroyed();
            } catch (MIDletStateChangeException e) {
                e.printStackTrace();
            }
        }
    	
        else if (c == cmdBack) {
        	si.setText("");
        	mainMenu();
        	
        	
        }
    }

    public void displayString(String string)
    {
    	//form.append(si);
    	si.setText(string);
        
    }
   
}

class Retriever extends Thread {
    private LocationDemo midlet;
    private String errorMsg = null;
    String query;
    public Retriever(LocationDemo midlet, String query){
        /**
          * Constructor
          *
          * EFFECTS: Initialise the server and store midlet information
          * @param midlet The main application midlet
          * @param server Forecast Server URL
          */
        this.midlet = midlet;
        this.query = query;
        System.out.println(query);
    }


    public void run(){
            /**
            * Entry point of the thread
            * EFFECTS: call to connect() method
            */
        
    	try {
    		   //Thread.sleep(000);
               String locString = "";
               locString = checkLocation();
               //put a new method which is check deals
               if(locString != null && locString.length()>0){
            	   getDeals(locString,query);
               }
               
            } catch (Exception ex){
               ex.printStackTrace();
               midlet.displayString(ex.toString());
               
            }
            
        }
       

    private synchronized void getDeals(String locString, String query) {
		
    	String URL   = "http://mlbs.no-ip.org:8080/MLBSWebApp/MlbsServlet?IMEI=0123456789&"+locString+"&"+"query="+query;
    	System.out.println("URL:"+URL);
    	//final String URL   = "http://75.36.214.107:8080/MLBSWebApp/MlbsServlet";
//		StringBuffer buffer = new StringBuffer();
		HttpConnection c = null;
		InputStream is = null;
		
		
		
		//if( menu.  )
		boolean ret = false;
          try {
			try {
			      // Display message that code is in startApp()
			      System.out.println("In getDeals .....\n\n");
			      // Open an HTTP connection to the URL. The connection supports
			      // the HTTP 1.1 protocol defined in the IETF RFC2616.
			      c = (HttpConnection)Connector.open(URL);	
			      // Open the InputStream using the HTTP connection that
			      // was established.
			     c.setRequestMethod(HttpConnection.GET);
			      // Opening the InputStream will open the connection
			      // and read the HTTP headers. They are stored until
			      // requested.
			      is = c.openInputStream();
			      ret = processServerResponse(c, is);
				}
			   finally {
			      if (is != null)
			          is.close();
			      if (c != null)
			          c.close();
			  }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
              
           
        
		if (ret == false){	
		    showAlert(errorMsg);       
		
		// Prints out the data read from the URL
		} 
		
	
    }


    private void showAlert(String errorMsg) {
		// TODO Auto-generated method stub
		
	}


	/*--------------------------------------------------
     * Process a response from a server
     *-------------------------------------------------*/
     private boolean processServerResponse(HttpConnection http, InputStream iStrm) throws IOException
     {
    	   System.out.println("In processServerResponse .....\n\n");

       //Reset error message
       errorMsg = null;
       
       // 1) Get status Line
       if (http.getResponseCode() == HttpConnection.HTTP_OK)
       {
	         // 2) Get header information - none
	         
	         // 3) Get body (data)
	         int length = (int) http.getLength();
	         String str;
	         if (length != -1)
	         {
	           byte servletData[] = new byte[length];
	           iStrm.read(servletData);
	           str = new String(servletData);
	           System.out.println("server response:"+str);

	           midlet.displayString(str);
	         }
	         else  // Length not available...
	         {
	           ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
	           
	           int ch;
	           while ((ch = iStrm.read()) != -1){
	             bStrm.write(ch);
	           }
	           str = new String(bStrm.toByteArray());
	           
	           str=str.replace('\n', ' ');
	           str=str.replace(';', '\n');
	           
	           bStrm.close();
	         }
	        
	        // Update the string item on the display
	       // siBalance.setText(str);
	         System.out.println("server response2:"+str);
	         midlet.displayString(str);
	        return true;
        
       }
       else{
         // Use message from the servlet
         errorMsg = new String( http.getResponseMessage());
         System.out.println("server response3:"+errorMsg);
       	 midlet.displayString(errorMsg);
         return false;
       }
     }

    
   


	public String checkLocation() throws Exception{
        String locString=null;
        Location l;
        LocationProvider lp;
        Coordinates c;
        System.out.println("running the checkLocation thread");
        //String cellID = System.getProperty("CellID");
      //  String lac = System.getProperty("LocAreaCode");
       // String imsi = System.getProperty("IMSI");
        //String imei = System.getProperty("phone.imei");
        
        //imei = System.getProperty("phone.imei");
     //   String mcc = imsi.substring(0,3);
     //   String mnc = imsi.substring(3,6);
       
       // string = " lac:"+lac+" imsi:"+imsi; 
        // Set criteria for selecting a location provider:
        // accurate to 500 meters horizontally
        Criteria cr= new Criteria();

        cr.setHorizontalAccuracy(500);

        // Get an instance of the provider

        lp= LocationProvider.getInstance(cr);
        

        // Request the location, setting a one-minute timeout
        l = lp.getLocation(60);


               c = l.getQualifiedCoordinates();

        if(c != null ) {
          // Use coordinate information
          double lat = c.getLatitude();
          double lon = c.getLongitude();
         //string = string+ "\nLatitude : " + lat + "\nLongitude : " + lon;
        	
    	 locString = "latitude="+lat+"&"+"longitude="+lon;
          //locString = "latitude="+37.358517+"&"+"longitude=-"+121.983518;
          //locString = locString + "latitude=&longitude=-"+lon;
    	 System.out.println("Lat / lon "+ locString);

        } else {
            locString ="Sorry, Cannot Retrieve Your Location";
            System.out.println("Lat / lon "+ locString);
        }
        //midlet.displayString(locString);
        return locString;
    }
}